import React from "react";
import PropTypes from 'prop-types';
import bindthis from 'autobind-decorator'
import {injectReducer} from "../store/reducers";
import {store} from "../main"
import Button from '@material-ui/core/Button';
import MDialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogContentText from '@material-ui/core/DialogContentText';
import DialogTitle from '@material-ui/core/DialogTitle';


@bindthis
export default class Dialog extends React.Component {

	static ACTION_NAME = "DIALOG";
	static contextTypes = {store: PropTypes.object.isRequired}
	static dispatcher = null

	state = {open: false, text: ":)", title: "", resolve: null, reject: null}

	static show(text, title = "提示") {
		return new Promise((resolve, reject) => store.dispatch({type: Dialog.ACTION_NAME, text: {text, title}, resolve, reject}))
	}

	constructor(props, context) {
		super(props, context)

		const {store} = context;

		const reducer = (state = "", action) => {
			if (action.type !== Dialog.ACTION_NAME)
				return state;

			this.setState({open: true, text: action.text.text, title: action.text.title, resolve: action.resolve, reject: action.reject})

			return action.text.text
		}

		injectReducer(store, {key: Dialog.ACTION_NAME, reducer})
	}

	handleClose() {
		this.state.reject("confirm canceled.")
		this.setState({open: false})
	}

	handleOK() {
		this.state.resolve()
		this.setState({open: false})
	}

	render() {
		return (
			<MDialog
				open={this.state.open}
				onClose={this.handleClose}
				aria-labelledby="alert-dialog-title"
				aria-describedby="alert-dialog-description"
				fullWidth={true}
			>
				<DialogTitle id="alert-dialog-title">{this.state.title}</DialogTitle>
				<DialogContent>
					<DialogContentText id="alert-dialog-description">
						{this.state.text}
					</DialogContentText>
				</DialogContent>
				<DialogActions>
					<Button onClick={this.handleClose} color="primary">
						取消
					</Button>
					<Button onClick={this.handleOK} color="primary" autoFocus>
						确认
					</Button>
				</DialogActions>
			</MDialog>
		)
	}
}

